import { reportError } from '../utils/request';
import { config } from '../utils/config';

const start = () => {
  const { jsAxiosError } = config;

  // js 异常捕获
  window.onerror = (message, location, lineno, colno, error) => {
    const { name, stack } = error;
    if (!jsAxiosError && error?.config?.isAxiosError) return; // 对 axios 错误的特殊处理
    reportError({
      type: 'js',
      name,
      message,
      location,
      lineno,
      colno,
      stack
    });
  };

  // 静态资源加载异常捕获
  window.addEventListener('error', (e) => {
    if (e.target !== window) {
      const { target } = e;
      reportError({
        type: 'static',
        sourceURI: target.src || target.href,
        location: target.baseURI,
        nodeName: target.nodeName,
        outerHTML: target.outerHTML
      });
    }
  }, true);

  // Promise 异常捕获
  window.addEventListener('unhandledrejection', (e) => {
    throw e.reason; // 抛出给 window.onerror 处理
  });
};

export default start;
